package com.dongnao.jack.registry.handler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;

import com.alibaba.fastjson.JSONObject;
import com.dongnao.jack.spring.parse.ProtocolConfig;
import com.dongnao.jack.spring.parse.RegistryConfig;

/**
 * 
 * @ClassName: JedisServiceRegistryHandler 
 * @Description:jedis服务注册器处理过程
 * @author xuyp
 * @date 2018年4月20日 下午2:17:05 
 *
 */
public class JedisServiceRegistryHandler implements ServiceRegistryHandler {

    private String flag = "redis";

    @Override
    public boolean serviceregistry(String ref, String className, ApplicationContext context) {

        try {

            // Object bean = context.getBean(ref, Class.forName(className));
            RegistryConfig jedisRegistryConfig = getJedisRegistryConfig(context);
            RegistryConnection connection = JedisRegistryConnection.createInstance(jedisRegistryConfig);

            ProtocolConfig protocolConfig = context.getBean(ProtocolConfig.class);

            JedisServiceConfigBean servicebean = new JedisServiceConfigBean();
            servicebean.setHostAndIp(protocolConfig.getHost() + ":" + protocolConfig.getPort());
            servicebean.setProtocol(protocolConfig);
            servicebean.setRef(ref);
            return connection.lpush(className, JSONObject.toJSONString(servicebean));
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        return false;

    }

    private RegistryConfig getJedisRegistryConfig(ApplicationContext context) {

        Map<String, RegistryConfig> map = context.getBeansOfType(RegistryConfig.class);
        if (map.containsKey("redis")) {
            return map.get("redis");
        }

        for (RegistryConfig config : map.values()) {

            if (config.getProtocol().equals("redis")) {
                return config;
            }

        }

        return null;

    }

    public boolean support(String anFlag) {
        return flag.equals(anFlag);
    }

    @Override
    public List<String> getRegistry(String className, ApplicationContext context) {

        RegistryConfig jedisRegistryConfig = getJedisRegistryConfig(context);
        RegistryConnection connection = JedisRegistryConnection.createInstance(jedisRegistryConfig);

        String lrangeString = connection.lrangeString(className);

        List parseObject = JSONObject.parseObject(lrangeString, List.class);

        List<String> list = new ArrayList<>(parseObject.size());
        for (int i = 0; i < parseObject.size(); i++) {
            Object object = parseObject.get(i);
            System.out.println(object);
            list.add(i, object.toString());
        }
        return list;
    }

}
